<template>
  <div class="content-wrap">
    <!-- 检索区域 -->
    <el-form class="search-wrap" :inline="true" :model="searchFormData">
      <!-- 测试人员 -->
      <el-form-item class="search-wrap-item" label="测试人员：">
        <el-select class="search-select" size="default" placeholder="全部" v-model="searchFormData.testId" clearable
          filterable @change="handleSearch">
          <el-option v-for="item in testOptions" :key="item.id" :label="item.nickName" :value="item.id" />
        </el-select>
      </el-form-item>
      <!-- 项目名称 -->
      <el-form-item class="search-wrap-item" label="项目名称：">
        <el-select class="search-select" placeholder="全部" v-model="searchFormData.projectid" clearable filterable
          @change="handleSearch">
          <el-option v-for="item in projecOptions" :key="item.ID" :label="item.itemName" :value="item.ID" />
        </el-select>
      </el-form-item>
      <!-- 需求名称 -->
      <el-form-item class="search-wrap-item" label="需求名称：">
        <el-input v-model="searchFormData.requirementName" style="width: 200px" placeholder="请输入项目名称" clearable
                  @keyup.enter="handleSearch"></el-input>
      </el-form-item>
      <!-- 创建时间 -->
      <el-form-item class="search-wrap-item" label="创建时间：">
        <el-date-picker style="width: 240px" v-model="searchFormData.timeFrame" type="daterange" unlink-panels
          range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间" :shortcuts="shortcuts"
          @change="handleSearch" />
      </el-form-item>
      <el-form-item style="font-size: 12px; margin: 10px 0;">
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格区域 -->
    <el-card class="card-wrap" v-loading="loading" style="max-height: 780px">
      <div class="card-wrap-fun">
        <!-- 功能区域 -->
        <el-button type="primary" @click="initDialogForm(null)">
          <el-icon>
            <Plus />
          </el-icon>
          <span>添加需求</span>
        </el-button>
        <!-- 数据总览区域
        <div class="card-wrap-count">
          <span class="card-wrap-count-search" @click="shortcutSearch(9999)"
            >本月需求总数：{{ requireCountTotal }}</span
          >
          <span
            class="card-wrap-count-search"
            v-for="(item, index) in requireCountData"
            :key="index"
            @click="shortcutSearch(index)"
          >
            {{ item.testName }}：{{ item.reqirmentNumber }}
          </span>
        </div> -->
      </div>
      <!-- 数据展示区域 -->
      <div class="card-wrap-table">
        <el-table :data="demandsList" border :max-height="'650px'" style="width: 100%"
          :header-cell-style="tableHeaderStyle" :row-style="tableRowStyle">
          <el-table-column fixed type="index" label="序号" width="60" align="center" />
          <el-table-column label="测试人员" width="100" align="center">
            <template #="{ row }">
              <span>{{ row.trueTestName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="需求名称" header-align="center" min-width="360">
            <template v-slot="scope">
              <div style="display: flex; justify-content: space-between">
                <span class="cell-ellipsis">{{
                  scope.row.requirementName
                }}</span>
                <div style="display: flex; justify-content: space-between">
                  <el-badge v-if="scope.row.itemCases.length != 0" :value="scope.row.itemCases.length" class="item"
                    type="primary" :max="99" :offset="[0, 5]"></el-badge>
                  <el-badge v-if="scope.row.itemCases.length != 0"
                    :value="scope.row.itemCases.filter((item: any) => item.isAudit == 0).length" class="item" :max="99"
                    :offset="[10, 5]"></el-badge>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="提测版本" width="200" header-align="center">
            <template #="{ row }">
              <span class="cell-ellipsis">{{ row.requirementVersion }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="beginTime" label="开始时间" width="120" sortable :formatter="timeDate" align="center" />
          <el-table-column prop="endTime" label="结束时间" width="120" sortable :formatter="timeDate" align="center" />
          <el-table-column prop="truthEndTime" label="测试完成时间" width="140" sortable :formatter="timeDate"
            align="center" />
          <el-table-column prop="truthOnlineTime" label="实际上线时间" width="140" sortable :formatter="timeDate"
            align="center" />
          <el-table-column label="操作" align="center" width="160" fixed="right" border>
            <template #="{ row }">
              <!-- 查看需求 -->
              <!-- <el-tooltip content="查看需求" placement="bottom" effect="light"> -->
                <el-button type="primary" plain size="small" @click="handleViewRequire(row.ID)">
                  查看
                </el-button>
              <!-- </el-tooltip> -->
              <!-- 需求测试用例 -->
              <!-- <el-tooltip :content="(isUserAuthId == '111' || isUserAuthId == '888' || isUserAuthId == '999') ? '审核用例' : '上传用例' " placement="bottom" effect="light"> -->
                <el-button type="primary" plain size="small" @click="handleRowDblClick(row)">
                  {{ (isUserAuthId == '111' || isUserAuthId == '888' || isUserAuthId == '999') ? '审核用例' : '上传用例'}}
                </el-button>
              <!-- </el-tooltip> -->
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页区域 -->
      <div class="page-wrap">
        <Pagination v-model:currten-page="pageInfo.page" :page-size="pageInfo.pageSize" :total="pageInfo.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange"></Pagination>
      </div>
    </el-card>

    <!-- 添加/修改需求弹窗 -->
    <el-dialog id="dialogForm" v-model="dialogTableVisible" :title="titleDialogText + '需求'" width="800px"
      style="height: calc(100% - 100px); margin: 50px auto; overflow-y: auto;" :show-close="true" :before-close="handleBeforeCancel">
      <el-form class="dialog-form" :inline="true" ref="dialogFormRef" :model="dialogFormData" :rules="ruleDialogForm"
        label-position="left" label-width="120px">
        <el-form-item label="项目名称：" prop="projectid" required>
          <el-select style="width: 160px" placeholder="请选择项目" v-model="dialogFormData.projectid" clearable>
            <el-option v-for="item in projecOptions" :key="item.ID" :label="item.itemName" :value="item.ID" />
          </el-select>
        </el-form-item>
        <el-form-item label="需求名称：" prop="requirementName" required>
          <el-input v-model="dialogFormData.requirementName" placeholder="请输入需求名称"
            :input-style="{ width: '600px' }"></el-input>
        </el-form-item>
        <el-form-item label="需求详情：" prop="requirementContent" required>
          <EditorVue class="editor" :modelValue="dialogFormData.requirementContent"
            @update:modelValue="updateModelValue" />
        </el-form-item>
        <el-form-item label="提测版本：">
          <el-input v-model="dialogFormData.requirementVersion" placeholder="请输入提测版本"
            :input-style="{ width: '600px' }"></el-input>
        </el-form-item>
        <el-form-item label=" 开始时间：">
          <el-date-picker v-model="dialogFormData.beginTime" type="date" placeholder="请选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label=" 结束时间：">
          <el-date-picker v-model="dialogFormData.endTime" type="date" placeholder="请选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label=" 计划提测时间：">
          <el-date-picker v-model="dialogFormData.planBeginTime" type="date" placeholder="请选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label=" 实际提测时间：">
          <el-date-picker v-model="dialogFormData.truthBeginTime" type="date" placeholder="请选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="测试完成时间：">
          <el-date-picker v-model="dialogFormData.truthEndTime" type="date" placeholder="请选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="实际上线时间：">
          <el-date-picker v-model="dialogFormData.truthOnlineTime" type="date" placeholder="请选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
      </el-form>
      <!-- 添加需求时确认是否为当月需求 -->
      <el-dialog v-show="currentMonth" v-model="dialogCurrentMonthVisible" title="请确认是否为当月需求？">
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="handleFalse">否</el-button>
            <el-button type="primary" @click="handleTrue"> 是 </el-button>
          </div>
        </template>
      </el-dialog>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleAddRequire"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看需求 -->
    <!-- <el-dialog
      class="dialog-view-container"
      title="查看需求"
      :show-close="true"
      width="1200px"
      style="height: calc(100% - 100px); margin: 50px auto"
      v-model="dialogViewVisible"
    >
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">需求名称:</span>
        </el-col>
        <el-col :span="14">{{ dialogViewData.requirementName }}</el-col>
        <el-col :span="3">
          <span class="dialog-view-requireTitle">需求分数:</span>
        </el-col>
        <el-col :span="4">{{ dialogViewData.requirementMark }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">需求创建人:</span>
        </el-col>
        <el-col :span="14">{{ dialogViewData.requirementCreateName }}</el-col>
        <el-col :span="3">
          <span class="dialog-view-requireTitle">实际测试人:</span>
        </el-col>
        <el-col :span="4">{{ dialogViewData.trueTestName }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">提测版本:</span>
        </el-col>
        <el-col :span="21">{{ dialogViewData.requirementVersion }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">参与人员:</span>
        </el-col>
        <el-col :span="21">{{ dialogViewData.requirementRelevances }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">创建时间:</span>
        </el-col>
        <el-col :span="21">{{ dialogViewData.createAt }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">开始时间:</span>
        </el-col>
        <el-col :span="9">{{ dialogViewData.beginTime }}</el-col>
        <el-col :span="3">
          <span class="dialog-view-requireTitle">结束时间:</span>
        </el-col>
        <el-col :span="9">{{ dialogViewData.endTime }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">计划提测时间:</span>
        </el-col>
        <el-col :span="9">{{ dialogViewData.planBeginTime }}</el-col>
        <el-col :span="3">
          <span class="dialog-view-requireTitle">实际提测时间:</span>
        </el-col>
        <el-col :span="9">{{ dialogViewData.truthBeginTime }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">测试完成时间:</span>
        </el-col>
        <el-col :span="9">{{ dialogViewData.truthEndTime }}</el-col>
        <el-col :span="3">
          <span class="dialog-view-requireTitle">实际上线时间:</span>
        </el-col>
        <el-col :span="9">{{ dialogViewData.truthOnlineTime }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">需求详情:</span>
        </el-col>
        <el-col :span="21">
          <el-scrollbar style="max-height: 360px;">
            <div
              ref="content"
              :style="requirementContetnStyle"
              v-dompurify-html="dialogViewData.requirementContent"
            ></div>
          </el-scrollbar>
        </el-col>

        <el-dialog v-model="dialogVisible" width="80%" height="80%">
          <img
            :src="currentImageSrc"
            class="el-image-viewer__img"
            style="
              transform: scale(1) rotate(0deg) translate(0px, 0px);
              max-height: 100%;
              max-width: 100%;
            "
          />
        </el-dialog>
      </el-row>
    </el-dialog> -->

    <!-- 上传、审核用例 -->
    <el-dialog v-model="dialogTestVisible" title="需求用例" width="80%" :show-close="true" :before-close="closeCasesDialog">
      <!-- 上传用例 -->
      <el-upload ref="uploadCase" class="upload-demo" action="#" :limit="1" :before-upload="handleBeforeUpload">
        <template #trigger>
          <el-button type="primary">上传用例</el-button>
        </template>
        <template #tip>
          <p>{{ uploadTipText }}</p>
        </template>
      </el-upload>
      <!-- 用例数据表格 -->
      <el-scrollbar max-height="680px">
        <el-table height="600px" :data="initCaseData" border fit="false">
          <el-table-column fixed type="index" label="序号" width="60" align="center" />
          <el-table-column label="用例名称" min-width="200" header-align="center" property="caseName" show-overflow-tooltip
            fixed="left" border>
            <template #="{ row }">
              <span class="cell-ellipsis">{{ row.caseName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用例编写人" width="100" align="center" property="caseEditMembers"></el-table-column>
          <el-table-column label="更新时间" width="120" align="center" property="caseEditDate" sortable
            :formatter="timeDate" show-overflow-tooltip></el-table-column>
          <!-- <el-table-column label="更新时间" width="120" align="center" property="caseEditDate" sortable
            :formatter="timeDate"></el-table-column> -->
          <el-table-column label="用例得分" width="100" align="center" property="caseScore"></el-table-column>
          <el-table-column label="是否能复用" width="100" align="center" property="isCaseReuse">
            <template #="{ row }">
              <span :style="{ color: row.isCaseReuse == '否' ? 'red' : 'green' }">{{ row.isCaseReuse }}</span>
            </template>
          </el-table-column>
          <el-table-column label="是否是补充用例" width="100" align="center" property="isCaseAdd">
            <template #="{ row }">
              <span :style="{ color: row.isCaseAdd == '否' ? 'red' : 'green' }">{{ row.isCaseAdd }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用例质量" width="100" align="center" property="caseQuality">
            <template #="{ row }">
              <span :style="{ color: getQualityColor(row.caseQuality) }">{{
                row.caseQuality === 3
                  ? "优"
                  : row.caseQuality === 2
                    ? "良"
                    : "差"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="审核状态" width="100" align="center" property="isAudit">
            <template #="{ row }">
              <span :style="{ color: row.isAudit == 0 ? 'red' : 'green' }">{{
                row.isAudit === 0 ? "未审核" : "已审核"
              }}</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="150px" align="center" fixed="right" border>
            <template #="{ row }">
              <div style="width: 100%; display: flex; flex-direction: row; justify-content: center;">
                <!-- 审核 -->
                <el-button type="primary" size="small" plain @click="handleAuditTest(row)">
                  <el-icon>
                    <SetUp />
                  </el-icon>
                </el-button>
                <!-- 修改 -->
                <el-button v-if="isUserAuthId == '111'" id="addBtn" type="primary" size="small" plain
                  @click="handleEditTest(row)">
                  <el-icon>
                    <Edit />
                  </el-icon>
                </el-button>
                <!-- 删除 -->
                <el-popconfirm v-if="isUserAuthId == '111' || isUserAuthId == '666'" title="确定要删除该需求吗？" @confirm="handleDelTest(row.ID)"
                  @cancel="handleCancelDel">
                  <template #reference>
                    <el-button type="danger" size="small" plain>
                      <el-icon>
                        <Delete />
                      </el-icon>
                    </el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
    </el-dialog>

    <!-- 修改用例弹窗 -->
    <el-dialog title="用例详情" v-model="caseVisible" :show-close="true" :before-close="closeCaseDialog">
      <el-form ref="caseDlgFormRef" v-model="caseDlgFormData">
        <el-form-item label="用例名称:">
          <el-input type="text" v-model="caseDlgFormData.caseName" placeholder="请输入用例名称" />
        </el-form-item>
        <el-form-item label="操作步骤:">
          <el-input type="textarea" :rows="5" v-model="caseDlgFormData.operationSteps" placeholder="请输入操作步骤">
          </el-input>
        </el-form-item>
        <el-form-item label="预期结果:">
          <el-input type="textarea" :rows="5" v-model="caseDlgFormData.expectedResult" placeholder="请输入预期结果" />
        </el-form-item>
        <el-form-item label="实际结果:">
          <el-input type="textarea" :rows="5" v-model="caseDlgFormData.realResult" placeholder="请输入实际结果" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeCaseDialog">取消</el-button>
          <el-button type="primary" @click="submitCaseFormData">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核用例弹窗 -->
    <el-dialog v-model="auditVisible" :show-close="true" :before-colse="closeAuditDialog" title="审核用例">
      <!-- 用例详情 -->
      <ul class="case-info-wrap">
        <li class="case-info-item">
          <p class="case-info-title">用例名称：</p>
          <p class="case-info-text">{{ caseDlgFormData.caseName }}</p>
        </li>
        <li class="case-info-item">
          <p class="case-info-title">操作步骤：</p>
          <p class="case-info-text" v-html="caseDlgFormData.operationSteps"></p>
        </li>
        <li class="case-info-item">
          <p class="case-info-title">预期结果：</p>
          <p class="case-info-text" v-html="caseDlgFormData.expectedResult"></p>
        </li>
        <li class="case-info-item">
          <p class="case-info-title">实际结果：</p>
          <p class="case-info-text" v-html="caseDlgFormData.realResult"></p>
        </li>
      </ul>
      <!-- 审核用例 -->
      <el-form ref="auditFormRef" :model="auditFormData" v-if="isUserAuthId == '111'">
        <el-form-item label="用例质量:">
          <el-radio-group v-model="auditFormData.caseQuality">
            <el-radio :value="3">优</el-radio>
            <el-radio :value="2">良</el-radio>
            <el-radio :value="1">差</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用例得分:">
          <el-input-number v-model="auditFormData.caseScore" :min="0" size="small" />
        </el-form-item>
        <el-form-item label="是否能复用：">
          <el-switch v-model="auditFormData.isCaseReuse" inline-prompt active-value="是" inactive-value="否" />
        </el-form-item>
        <el-form-item label="是否是补充用例：">
          <el-switch v-model="auditFormData.isCaseAdd" inline-prompt active-value="是" inactive-value="否" />
        </el-form-item>
      </el-form>
      <template #footer v-if="isUserAuthId == '111'">
        <div class="dialog-footer">
          <el-button @click="closeAuditDialog">取消</el-button>
          <el-button type="primary" @click="submitAuditFormData">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 需求详情弹窗 -->
    <el-dialog v-if="dialogInfoVisible" style="width: 1200px" :close-on-click-modal="false" v-model="dialogInfoVisible"
      @close="dialogInfoVisible = false" @closed="dialogInfoVisible = false">
      <CommonRequirementInfoVue :isRequirementID="isRequirementID" :clearData="!dialogInfoVisible" :isComment="true">
      </CommonRequirementInfoVue>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// import EditorVue from "@/components/requirement/addBugMsg.vue";
import EditorVue from "@/views/experiment/demands/editor.vue";
import CommonRequirementInfoVue from "@/components/requirement/comomRequirementInfo.vue";
import { onMounted, ref, reactive, nextTick } from "vue";
import {
  postDemandsList,
  getItemList,
  getTestList,
  getRequirementsNumber,
  postAddRequirement,
  deleteRequirement,
  updateRequirement,
  postRequirement,
  getRequirementCase,
  postUploadCaseFile,
  postRequirementCase,
  delCaseByid,
  postAuditCaseByid,
  putEditeCaseByid,
  getCasesScoreNumber,
} from "@/api/project/index";
import { ElMessage } from "element-plus";
import Pagination from "@/components/Pagenation/index.vue";
import {
  getSearchTimes,
  getShortCuts,
  tableTimeDate,
  removeEmptyLines,
  tableTimeDateMsg2
} from "@/utils/utils";

//* 变量声明
const loading = ref(false);
const isUserAuthId = ref<any>();// 当前用户权限
const requireCountData = ref<any>([]); //当月各个测试人员需求数量
const requireCountTotal = ref(0); //当月需求总数
const casesCountData = ref<any>([]); //当月各个测试人员的用例条数及总分数
const demandsList = ref<any>([]); //所有需求数据列表
const projecOptions = ref<any>([]); //所有项目下拉列表
const testOptions = ref<any>([]); //所有的测试人员下拉列表

// 图片放大功能
// const dialogVisible = ref(false);
// const currentImageSrc = ref("");
// const content = ref<HTMLElement | null>(null);
//* 弹窗部分
const isCreateDialog = ref(false); //是否创建需求
const titleDialogText = ref(""); //添加或修改标题文本
const currentMonth = ref(false); //是否为当月需求

const dialogInfoVisible = ref(false);
const isRequirementID = ref<any>(null);

const dialogTableVisible = ref(false); //添加/修改需求弹窗控件
// const dialogViewVisible = ref(false); //查看需求弹窗控件
const dialogCurrentMonthVisible = ref(false); //是否为当月需求弹窗控件
const dialogTestVisible = ref(false); //查看、上传、审核用例弹窗控件
const caseVisible = ref(false); //修改用例弹窗控件
const auditVisible = ref(false); //审核用例弹窗控件

const uploadCaseFile = ref<File>(); //待上传文件
const uploadTipText = ref(""); //提示文字
const reqData = reactive({
  id: null,
  page: 1,
  pageSize: 999,
}); //获取当前需求所有用例的请求参数初始值
const reqCaseData = reactive({
  requirementId: null,
  itemItemId: null,
  filePath: "",
}); //导入用例请求参数

const initCaseData = ref<any>([]); //用例表格初始值

const dialogFormRef = ref(); //添加/修改需求表单实例
const requireID = ref(); //需求id

// 需求表单数据类型声明
interface DialogFormData {
  id?: undefined;
  thisMonthReqirement?: number;
  requirementName: string;
  requirementCreateName: string;
  requirementContent: string;
  requirementVersion: string;
  beginTime: any;
  endTime: any;
  planBeginTime: any;
  truthBeginTime: any;
  truthEndTime: any;
  truthOnlineTime: any;
  projectid: number | null;
}

// 初始化表单数据
const initDialogFormData = () => ({
  thisMonthReqirement: 1,
  requirementName: "",
  requirementCreateName: "",
  requirementContent: "",
  requirementVersion: "",
  beginTime: null,
  endTime: null,
  planBeginTime: null,
  truthBeginTime: null,
  truthEndTime: null,
  truthOnlineTime: null,
  projectid: null,
});
const dialogFormData: DialogFormData = reactive(initDialogFormData());
// 弹窗表单校验规则
const ruleDialogForm = reactive({
  projectid: [
    {
      required: true,
      message: "请选择项目名称",
      trigger: "blur",
    },
  ],
  requirementName: [
    {
      required: true,
      message: "请填写需求名称",
      trigger: "blur",
    },
  ],
  requirementContent: [
    {
      required: true,
      message: "请描述需求详情",
      trigger: "blur",
    },
  ],
  thisMonthReqirement: [
    {
      required: true,
      message: "请确认是否为本月需求？",
      trigger: "blur",
    },
  ],
});

const pageInfo = reactive({
  total: 0, //总条目
  page: 1, //当前页码
  pageSize: 20, //当前每页条数
});
//关键词数据默认值
const searchFormData = reactive({
  testId: null,
  projectid: null,
  requirementName: "",
  timeFrame: getSearchTimes(new Date()),
});

// 自定义table样式
const tableHeaderStyle = {
  backgroundColor: "#F2F6FC",
  color: "#909399",
  textAlign: "center",
};
const tableRowStyle = {
  cursor: "pointer",
  backgroundColor: "#fff",
};

// const requirementContetnStyle: { [key: string]: string } = {
//   whiteSpace: "wrap",
//   lineHeight: "200%",
//   cursor: "pointer",
// };

// 查看需求初始值
// const dialogViewData: any = reactive({
//   requirementName: "",
//   requirementMark: 0,
//   requirementVersion: "",
//   requirementRelevances: "无",
//   requirementCreateName: "",
//   trueTestName: "",
//   createAt: "0001-01-01T00:00:00Z",
//   beginTime: "0001-01-01T00:00:00Z",
//   endTime: "0001-01-01T00:00:00Z",
//   planBeginTime: "0001-01-01T00:00:00Z",
//   truthBeginTime: "0001-01-01T00:00:00Z",
//   truthEndTime: "0001-01-01T00:00:00Z",
//   truthOnlineTime: "0001-01-01T00:00:00Z",
//   requirementContent: "",
// });

//? 修改用例
// 表单实例
const caseDlgFormRef = ref();
// 表单初始化方法
const initCaseDlgFormData = () => ({
  id: null,
  caseName: "",
  operationSteps: "",
  expectedResult: "",
  realResult: "",
});
//表单初始值
const caseDlgFormData = reactive(initCaseDlgFormData());

//? 审核用例
const auditFormRef = ref();
const initAduditFormData = () => ({
  id: null,
  caseQuality: 3,
  caseScore: 100,
  isCaseReuse: <any>"否",
  isCaseAdd: <any>"否",
  isAudit: 1,
});
const auditFormData = reactive(initAduditFormData());

//* 功能函数
// 时间快捷选择器
const shortcuts = getShortCuts();

// @ts-ignore 时间格式化
const timeDate = (row: any, column: any, cellValue: any, index: number) => {
  return tableTimeDate(cellValue);
};

// 获取所有需求数据列表-demandsList
const getDemandsList = async () => {
  loading.value = true;
  isUserAuthId.value = localStorage.getItem("authorityId");

  console.log("测试id：", searchFormData.testId);
  const resData = await postDemandsList({
    testId: searchFormData.testId !== "" ? searchFormData.testId : null,
    projectid: searchFormData.projectid !== "" ? searchFormData.projectid : null,
    requirementName: searchFormData.requirementName,
    createAtBegin:
      searchFormData.timeFrame !== null
        ? searchFormData.timeFrame[0]
        : "0001-01-01T00:00:00Z",
    createAtEnd:
      searchFormData.timeFrame !== null
        ? new Date(new Date(searchFormData.timeFrame[1]).setHours(23, 59, 59))
        : new Date(),
    page: pageInfo.page,
    pageSize: pageInfo.pageSize,
  });

  if (resData.data.code === 200 && resData.data.data.list !== null) {
    pageInfo.total = resData.data.data.total;
    pageInfo.page = resData.data.data.page;
    pageInfo.pageSize = resData.data.data.pageSize;
    demandsList.value = resData.data.data.list; //所有需求数据列表
  } else {
    ElMessage.error("获取数据失败");
    loading.value = false;
    return;
  }
  loading.value = false;
};

// 获取当月需求汇总数据
const getRequirementsList = async () => {
  const resData = await getRequirementsNumber();
  if (resData.data.code == 7) {
    ElMessage.error(resData.data.msg);
    throw new Error(resData.data.msg);
  } else {
    requireCountData.value = resData.data.data;
    if (requireCountData.value.length !== 0) {
      requireCountTotal.value = requireCountData.value.reduce((sum: any, item: any) => {
        return sum + item.reqirmentNumber;
      }, 0);
    }
  }
};
// 获取当月用例条数和分数
const getCasesCount = async () => {
  const resData = await getCasesScoreNumber();
  if (resData.data.code == 7) {
    ElMessage.error(resData.data.msg);
    throw new Error(resData.data.msg);
  } else {
    casesCountData.value = resData.data.data;
  }
};

// 更改每页条目数
const handleSizeChange = async (val: number) => {
  pageInfo.pageSize = val;
  pageInfo.page = 1;
  await getDemandsList();
};
// 更改当前页码
const handleCurrentChange = async (val: number) => {
  pageInfo.page = val;
  await getDemandsList();
};

// 获取所有项目下拉列表-projecOptions
const getProjectOptons = async () => {
  loading.value = true;
  const resData = await getItemList({});
  if (resData.data.code === 200 && resData.data.data.length != 0) {
    // 所有项目下拉列表
    projecOptions.value = resData.data.data.map((item: any) => {
      return { ID: item.ID, itemName: item.itemName };
    });
  } else {
    ElMessage.error("未获取到项目数据列表");
    loading.value = false;
    return;
  }
  loading.value = false;
};

//! 获取所有测试人员列表-testOptions
const getAllTestOptions = async () => {
  loading.value = true;
  const resData = await getTestList();
  if (resData.data.code === 200 && resData.data.data.length != 0) {
    // 所有测试人员下拉列表
    testOptions.value = resData.data.data;

  } else {
    ElMessage.error("未获取到测试人员列表");
    loading.value = false;
    return;
  }

  loading.value = false;
};

// 搜索功能
const handleSearch = async () => {
  loading.value = true;
  await getDemandsList();
  loading.value = false;
};

//* 双击单个需求时触发事件-该需求下的所有测试用例
const handleRowDblClick = async (row: any) => {
  dialogTestVisible.value = true; //开启弹窗
  initCaseData.value = []; // 表格数据初始化
  reqData.id = row.ID;
  reqCaseData.requirementId = row.ID;
  reqCaseData.itemItemId = row.ItemItemId;

  // 根据需求获取所有用例
  const resData = await getRequirementCase(reqData);
  if (resData.data.code === 200 && resData.data.data.list !== null) {
    initCaseData.value = resData.data.data.list;
  } else {
    ElMessage.error(resData.data.msg);
    return;
  }
};

// 选择文件后临时保存
const handleBeforeUpload = async (file: any) => {
  uploadCaseFile.value = file;
  if (uploadCaseFile.value == undefined) {
    uploadTipText.value = "请先选择用例";
  } else {
    // 选择并上传用例
    const resData = await postUploadCaseFile(uploadCaseFile.value);
    // 上传成功则直接导入用例
    if (resData.data.code === 200) {
      ElMessage.success(resData.data.msg);
      reqCaseData.filePath = resData.data.data.resultFilePath;

      // 导入用例
      const resCaseData = await postRequirementCase(reqCaseData);
      // 导入用例成功则刷新用例表格
      if (resCaseData.data.code === 200) {
        ElMessage.success(resCaseData.data.msg);
        await getDemandsList();

        // 重新获取用例
        const resDataList = await getRequirementCase(reqData);
        if (
          resDataList.data.code === 200 &&
          resDataList.data.data.list !== null
        ) {
          initCaseData.value = resDataList.data.data.list;
        } else {
          // 获取用例失败提示
          ElMessage.error(resDataList.data.msg);
          throw Error(resDataList.data.msg);
        }
      } else {
        // 导入失败提示
        ElMessage.error(resCaseData.data.msg);
        throw Error(resCaseData.data.msg);
      }
    } else {
      // 上传失败提示
      ElMessage.error(resData.data.msg);
      throw new Error(resData.data.msg);
    }
  }
  return false;
};

// 关闭/取消用例弹窗事件
const closeCasesDialog = () => {
  dialogTestVisible.value = false; //关闭弹窗
  reqData.id = null;
  reqCaseData.filePath = "";
  reqCaseData.itemItemId = null;
  reqCaseData.requirementId = null;
};
// 关闭/取消修改用例弹窗事件
const closeCaseDialog = () => {
  caseVisible.value = false; //关闭弹窗
  initCaseDlgFormData(); //初始化表单数据
};

// 关闭/取消审核用例弹窗事件
const closeAuditDialog = () => {
  auditVisible.value = false;
  initAduditFormData();
  initCaseDlgFormData();
};

// 定义不同用例质量的颜色
const getQualityColor = (quality: number) => {
  switch (quality) {
    case 3:
      return "green"; // 优 - 绿色
    case 2:
      return "blue"; // 良 - 蓝色
    default:
      return "red"; // 差 - 红色
  }
};

// 确认删除用例
const handleDelTest = async (id: number) => {
  const resData = await delCaseByid(id);
  if (resData.data.code === 200) {
    ElMessage.success(resData.data.msg);
    // 重新获取用例
    const resDataList = await getRequirementCase(reqData);
    if (resDataList.data.code === 200 && resDataList.data.data.list !== null) {
      initCaseData.value = resDataList.data.data.list;
    } else {
      // 获取用例失败提示
      ElMessage.error(resDataList.data.msg);
      throw Error(resDataList.data.msg);
    }
  } else {
    ElMessage.error(resData.data.msg);
    throw new Error(resData.data.msg);
  }
};
// 开启审核用例弹窗
const handleAuditTest = async (row: any) => {
  auditVisible.value = true;
  initAduditFormData(); //初始化表单数据
  auditFormData.id = row.ID;
  auditFormData.caseQuality = row.caseQuality;
  auditFormData.caseScore = row.caseScore;
  auditFormData.isCaseReuse = row.isCaseReuse;
  auditFormData.isCaseAdd = row.isCaseAdd;
  auditFormData.isAudit = row.isAudit;

  // 用例信息
  initCaseDlgFormData(); //表单初始化
  caseDlgFormData.id = row.ID;
  caseDlgFormData.caseName = row.caseName;
  caseDlgFormData.operationSteps = row.operationSteps.replace(/\n/g, "<br />");
  caseDlgFormData.expectedResult = row.expectedResult.replace(/\n/g, "<br />");
  caseDlgFormData.realResult = row.realResult.replace(/\n/g, "<br />");
};

// 提交审核数据
const submitAuditFormData = async () => {
  auditFormData.isAudit = 1;
  const resData = await postAuditCaseByid(auditFormData);
  if (resData.data.code == 200) {
    ElMessage.success(resData.data.msg);
    // 重新获取用例
    const resDataList = await getRequirementCase(reqData);
    if (resDataList.data.code === 200 && resDataList.data.data.list !== null) {
      initCaseData.value = resDataList.data.data.list;
    } else {
      // 获取用例失败提示
      ElMessage.error(resDataList.data.msg);
      throw Error(resDataList.data.msg);
    }
  } else {
    ElMessage.error(resData.data.msg);
    throw new Error(resData.data.msg);
  }
  await getDemandsList();
  auditVisible.value = false;
};

// 开启修改用例弹窗
const handleEditTest = (row: any) => {
  caseVisible.value = true;
  initCaseDlgFormData(); //表单初始化
  caseDlgFormData.id = row.ID;
  caseDlgFormData.caseName = row.caseName;
  caseDlgFormData.operationSteps = row.operationSteps;
  caseDlgFormData.expectedResult = row.expectedResult;
  caseDlgFormData.realResult = row.realResult;
};

// 提交修改后的用例
const submitCaseFormData = async () => {
  const resData = await putEditeCaseByid(caseDlgFormData);
  if (resData.data.code == 200) {
    ElMessage.success(resData.data.msg);
    // 重新获取用例
    const resDataList = await getRequirementCase(reqData);
    if (resDataList.data.code === 200 && resDataList.data.data.list !== null) {
      initCaseData.value = resDataList.data.data.list;
    } else {
      // 获取用例失败提示
      ElMessage.error(resDataList.data.msg);
      throw Error(resDataList.data.msg);
    }
  } else {
    ElMessage.error(resData.data.msg);
    throw new Error(resData.data.msg);
  }
  caseVisible.value = false;
};

//* 添加/修改弹窗表单校验
const validateForm = (form: any) => {
  return new Promise<boolean>((resolve, reject) => {
    form.validate((valid: boolean) => {
      if (valid) {
        resolve(true);
      } else {
        reject(new Error("请按要求填写需求！"));
      }
    });
  });
};

//!!! 开启添加/修改需求弹窗
const initDialogForm = async (row: any) => {
  dialogTableVisible.value = true;
  initDialogFormData(); //表单初始化
  if (row !== null) {
    //* 修改需求
    isCreateDialog.value = false;
    currentMonth.value = false;
    titleDialogText.value = "修改";
    // 其它非测试人员默认为其它
    if (row.ItemItemId == 0) {
      dialogFormData.projectid = 32;
    } else {
      dialogFormData.projectid = row.ItemItemId; //项目ID
    }
    requireID.value = row.ID; //需求ID
    const resData = await postRequirement({ id: row.ID }); //根据需求id获取需求信息
    const data = resData.data.data;
    if (resData.data.code === 7) {
      ElMessage.error(resData.data.msg);
      throw new Error();
    } else {
      dialogFormData.requirementName = data.requirementName;
      dialogFormData.requirementContent = data.requirementContent;
      dialogFormData.beginTime =
        data.beginTime == "" ? null : data.beginTime;
      dialogFormData.endTime =
        data.endTime == "" ? null : data.endTime;
      dialogFormData.planBeginTime =
        data.planBeginTime == ""
          ? null
          : data.planBeginTime;
      dialogFormData.truthBeginTime =
        data.truthBeginTime == ""
          ? null
          : data.truthBeginTime;
      dialogFormData.truthEndTime =
        data.truthEndTime == "" ? null : data.truthEndTime;
      dialogFormData.truthOnlineTime =
        data.truthOnlineTime == ""
          ? null
          : data.truthOnlineTime;
      dialogFormData.requirementVersion = data.requirementVersion;
      dialogFormData.thisMonthReqirement = data.thisMonthReqirement;
    }
  } else {
    //* 添加需求
    isCreateDialog.value = true;
    titleDialogText.value = "添加";
    currentMonth.value = true;
    dialogFormData.thisMonthReqirement = 1;
  }
};

// 富文本数据更新
const updateModelValue = (newContent: any) => {
  dialogFormData.requirementContent = newContent;
  return dialogFormData.requirementContent;
};

// 不是本月需求
const handleFalse = async () => {
  dialogFormData.thisMonthReqirement = 2;

  const resData = await postAddRequirement(dialogFormData).finally(() => {
    // 无论表单提交是否成功，都执行
    dialogTableVisible.value = false;
    dialogCurrentMonthVisible.value = false;
    loading.value = false;
    Object.assign(dialogFormData, initDialogFormData());
  });
  if (resData.data.code == 200) {
    ElMessage.success(`${titleDialogText.value}需求成功！`);
    await getDemandsList(); //重新获取所有需求数据
  } else {
    ElMessage.error(resData.data.msg);
    throw new Error();
  }
};
// 是本月需求
const handleTrue = async () => {
  dialogFormData.thisMonthReqirement = 1;

  const resData = await postAddRequirement(dialogFormData).finally(() => {
    // 无论表单提交是否成功，都执行
    dialogTableVisible.value = false;
    dialogCurrentMonthVisible.value = false;
    loading.value = false;
    Object.assign(dialogFormData, initDialogFormData());
  });
  if (resData.data.code == 200) {
    ElMessage.success(`${titleDialogText.value}需求成功！`);
    await getDemandsList(); //重新获取所有需求数据
  } else {
    ElMessage.error(resData.data.msg);
    throw new Error();
  }
};

//* 确定添加/修改需求功能
const handleAddRequire = async () => {
  loading.value = true;
  // 确定时监听富文本内容
  const addBtn = document.querySelector("#addBtn");
  addBtn?.addEventListener("update:modelValue", updateModelValue);

  // 提交需求到服务器
  if (isCreateDialog.value) {
    // * 添加需求
    dialogFormData.id = undefined;
    await validateForm(dialogFormRef.value);
    dialogCurrentMonthVisible.value = true;
  } else {
    // * 修改需求
    dialogFormData.id = requireID.value;
    dialogCurrentMonthVisible.value = false;
    dialogFormData.thisMonthReqirement = undefined;
    // @ts-ignore
    const resData = await updateRequirement(dialogFormData).finally(() => {
      // 无论表单提交是否成功，都执行
      dialogTableVisible.value = false;
      loading.value = false;
      Object.assign(dialogFormData, initDialogFormData());
    });
    if (resData.data.code == 200) {
      ElMessage.success(`${titleDialogText.value}需求成功！`);
      await getDemandsList(); //重新获取所有需求数据
    } else {
      ElMessage.error(resData.data.msg);
      throw new Error();
    }
  }
};

// 取消/关闭添加/修改需求
const handleCancel = () => {
  dialogTableVisible.value = false;
  Object.assign(dialogFormData, initDialogFormData());
};
const handleBeforeCancel = (done: any) => {
  dialogTableVisible.value = false;
  Object.assign(dialogFormData, initDialogFormData());
  done();
};

//* 查看需求功能
const handleViewRequire = async (index: number) => {
  dialogInfoVisible.value = true;
  isRequirementID.value = index;
};

// 取消删除需求
const handleCancelDel = () => {
  ElMessage.info("取消删除！");
  return;
};

onMounted(() => {
  getRequirementsList();
  getCasesCount();
  getProjectOptons();
  getAllTestOptions();
  getDemandsList();
  window.addEventListener("update:modelValue", updateModelValue);
});
</script>

<style scoped lang="scss">
// 文本溢出省略
.cell-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

// 快捷筛选
.card-wrap-count-search {
  display: inline-block;
  padding: 5px;
  margin-right: 10px;
  background-color: #f2f3f5;
  border-radius: 2px;
  cursor: pointer;
}

.card-wrap-count-search:hover {
  background-color: #a0cfff;
}

// 操作按钮
.table-operation {
  width: 36px;
  height: 26px;
  padding: 0 10px;
  display: inline-block;
  color: #409eff;
}

.table-operation-view:hover,
.table-operation-edit:hover {
  background-color: #409eff;
  color: white;
}

.table-operation-del:hover {
  background-color: #ff343f;
  color: white;
}
.search-wrap {
  padding: 0 10px!important;
}
.search-wrap-item {
  margin-bottom: 0!important;
}
/* 添加需求弹窗 */
.el-dialog {
  --el-dialog-margin-top: 20px;

  .dialog-form {
    .el-form-item {
      padding-left: 5px;
    }
  }
}

/* 查看需求 */
.dialog-view-requireTitle {
  font-weight: bold;
}

.el-row {
  border-left: 1px solid #eee;
  border-right: 1px solid #eee;
  text-align: left;
}

.el-col {
  border: 1px solid #eee;
  padding: 10px 0;
}

/* 用例总览区域 */
.case-item {
  display: flex;
  justify-content: space-between;
  margin-top: 5px;
  color: #303133;

  p {
    background-color: #f2f3f5;
    border-radius: 2px;
    padding: 5px 10px;
  }
}

/* 审核用例详情 */
.case-info-wrap {
  width: 100%;
  display: flex;
  flex-direction: column;

  .case-info-item {
    display: flex;
    justify-content: left;

    .case-info-title {
      width: 90px;
      margin-bottom: 20px;
      line-height: 150%;
    }

    .case-info-text {
      line-height: 150%;
      margin-bottom: 20px;
    }
  }
}
</style>

<style lang="scss">
.is-dark {
  width: 200px;
  opacity: 0.8;
}

.el-table {
  --el-table-row-hover-bg-color: #d9ecff;
}

.el-dialog {
  --el-dialog-margin-top: 50px;
}

.el-dialog__body {
  padding: 10px 20px 0px;
}
</style>
